<template>
  <div
    class="page-container container"
    style="height: auto"
    v-loading="state.loading"
  >
    <docDetailInformaton
      :detailData="state.detailData"
      ref="docDetailInformatonRef"
      :consignmentNoList="consignmentNoList"
      @getBookingState="getBookingState"
    ></docDetailInformaton>
    <docDetailTabCopy
      class="tab"
      @save="save"
      @edit="openEdit"
      :showBtn="showBtn"
      @refresh="refresh"
      @cancle="cancle"
      @exportWaybill="setBookingState"
    ></docDetailTabCopy>
    <div class="tab-all-container content" style="padding: 0px">
      <el-form
        ref="form"
        size="small"
        label-suffix="："
        :label-width="'100px'"
        :inline="true"
        :model="state.detailData"
        class="form"
      >
        <el-tabs
          v-model="state.activeName"
          @tab-change="tabClick"
          type="border-card"
        >
          <el-tab-pane label="操作详情" name="操作详情">
            <docDetailBaseCopy
              ref="docDetailBaseRef"
              v-model:detailData="state.detailData"
              :initOption="state.allOption"
              :disPlayRuels="disPlayRuels"
              :showBookingSearch="showBookingSearch"
              :showBookingInput="showBookingInput"
              :isBooking="state.isBooking"
            ></docDetailBaseCopy>
          </el-tab-pane>
          <el-tab-pane
            label="装箱信息"
            name="装箱信息"
            :disabled="canSwitchTab"
          >
            <docDetailBoxCopy
              v-model:detailData="state.detailData"
              :detailDataCopy="detailDataCopy"
              @refreshStep="refreshStep"
              :showBtn="showBtn"
              ref="docDetailBoxRef"
            >
            </docDetailBoxCopy>
          </el-tab-pane>
          <el-tab-pane
            label="费用信息"
            name="费用信息"
            :disabled="canSwitchTab"
          >
            <docDetailFee
              :detailData="state.detailData"
              ref="docDetailFeeRef"
              :showBtn="showBtn"
            >
            </docDetailFee>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <docDetailFileDialog
      v-model:show="state.fileShow"
      v-model:detailData="state.detailData"
      ref="docDetailFileDialogRef"
    >
    </docDetailFileDialog>
  </div>
</template>

<script setup>
import {
  defineComponent,
  computed,
  onMounted,
  reactive,
  ref,
  provide,
  onDeactivated,
  onUnmounted
} from 'vue'
import docDetailInformaton from './components/docDetailInformaton.vue'
import docDetailTabCopy from './newBusiness/docDetailTabCopy.vue'
import docDetailBaseCopy from './newBusiness/docDetailBaseCopy.vue'
import docDetailBoxCopy from './newBusiness/docDetailBoxCopy.vue'
import docDetailFee from './newBusiness/docDetailFee.vue'
import docDetailSpecialBoxNew from './newBusiness/docDetailSpecialBoxNew.vue'
import docDetailFileDialog from './components/docDetailFileDialog.vue'
import optionsStore from './newBusiness/getAllSelectOptionNew'
import dayjs from 'dayjs'
import request from '@/public/request'
import { useRouter, useRoute } from 'vue-router'
import { useStore, Store } from 'vuex'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import vueBus from '@/utils/vueBus'

// 路由和store相关
const Router = useRouter()
const Route = useRoute()
const store = useStore()

//控制页面显示状态
const disPlayRuels = computed(() => {
  // 如果是创建订舱时进来,页面只有委托信息可以编辑
  if (state.routeQuery.establish) {
    return true
  } else {
    if (state.allCanFill) {
      return true
    } else {
      return false
    }
  }
})

// 控制装箱信息和费用信息的tab是否可以点击
const canSwitchTab = computed(() => {
  // 当前为订舱创建跳转过来并且订舱时间为空时，禁止点击
  if (state.routeQuery.establish) {
    return true
  } else {
    // 点击编辑或者回填订舱信息确认tab是否可以进行点击
    if ((state.allCanFill || state.isBackfill) && !state.isBooking) {
      return true
    }
    if ((state.allCanFill || state.isBackfill) && state.isBooking) {
      return false
    }
    // 通过列表点击跳转过来，可以进行点击查看
    if (state.routeQuery.isJump) {
      return false
    } else {
      if (state.isBooking) {
        return false
      }
    }
  }
})

// 控制保存与取消和编辑与导出脱单的按钮显示
const showBtn = computed(() => {
  if (state.routeQuery.establish || state.isBackfill || state.allCanFill) {
    return true
  } else {
    return false
  }
})

// 显示暂无订舱和订舱信息
const showBookingSearch = computed(() => {
  // 如果是点击回填必须显示订舱信息
  if (state.isBackfill) {
    return false
  }
  if (state.routeQuery.establish || !state.detailData.blno) {
    return true
  } else {
    return false
  }
})
// 显示是否有输入框
const showBookingInput = computed(() => {
  if (state.isBackfill || (state.allCanFill && state.isBooking)) {
    return true
  } else {
    return false
  }
})

// 点击编辑，让页面可以编辑
function openEdit() {
  state.allCanFill = true
  // 当前为订舱创建跳转过来并且订舱时间为空时，禁止点击
  if (!state.routeQuery.establish && !state.isBooking) {
    state.activeName = '操作详情'
  }
}

function setBookingState() {
  state.isBackfill = true
  // 当前为订舱创建跳转过来并且订舱时间为空时，禁止点击
  if (!state.routeQuery.establish && !state.isBooking) {
    state.activeName = '操作详情'
  }
}

// 所有基础数据相关
const state = reactive({
  activeName: '操作详情',
  routeData: {
    id: '',
    title: '',
    iscopy: false
  },
  //所有数据
  detailData: {
    id: undefined,
    bookingState: 0, //状态
    doccode: undefined, //单号
    blno: undefined, //提单号
    bookingNo: undefined, //BOOKING
    contractNumber: undefined, //合约号
    shipingAgent: undefined, //船代
    shipingAgentCode: undefined, //船代Code
    vessel: undefined, // 船名
    shipId: '',
    voyage: undefined, // 航次
    berthWharf: undefined, // 靠泊码头
    enterPortCode: undefined, // 航次
    requester: undefined, // 委托单位
    requesterCode: undefined,
    consignmentNo: undefined, // 托运编号
    cargoSource: undefined, // 货物来源
    preDeliveryDate: undefined, // 货好时间
    bookingParty: undefined, //订舱单位
    bookingPartyCode: undefined,
    billType: undefined, //签单方式
    originalBillNumber: undefined, //正本份数
    originalBillCopyNumber: undefined, //副本份数
    signingLocation: undefined, //签单地点
    bookingAgent: undefined, //订舱代理
    bookAgentCode: undefined, //订舱代理
    freightTerms1: undefined, //运输条款
    freightTerms2: undefined,
    carriageConditions: undefined,
    payment: undefined, // 付款方式
    payPlace: undefined, // 付款地点
    shipowner: undefined, // 船公司
    loadingPort: undefined, // 装货港
    loadingPortCode: undefined,
    receiptPlace: undefined, // 装货地点
    receiptPlaceCode: undefined,
    transshipmentPort: undefined, // 中转港
    transshipmentPortCode: undefined,
    // shipcompanyId: undefined, // 港口航线
    portRoute: undefined, // 港口航线
    dischargePort: undefined, // 卸货港
    dischargePortCode: undefined,
    unloadingPlace: undefined, // 卸货地点
    unloadPlaceCode: undefined,
    finalDestination: undefined, // 目的地
    finalDestinationCode: undefined,
    fclLcl: undefined, // 托运类型
    pkgs: undefined, //件数
    packageType: undefined, //包装类型
    hscode: undefined, //HS CODE
    cargoName: undefined, //英文品名
    grossWeight: undefined, //毛重
    cargoNameCn: undefined, //中文品名
    measurement: undefined, //体积
    memo: undefined, //订舱备注
    otherRemark: undefined, //其他备注
    shipperConsignees: [], //收发通数组
    coldDangers: [], //特货信息冷藏品数组
    containers: [], //集装箱列表

    fees: [], //全部费用明细表
    // containerSums
    containerSums: [
      {
        id: 0,
        index: 0,
        bookingId: 0,
        ctnType: '',
        ctnDigit: 1,
        tareWeight: 1,
        isDeleted: false,
        ctnOwner: ''
      }
    ], //箱型向量
    containerSumsCopy: [
      {
        id: 0,
        index: 0,
        bookingId: 0,
        ctnType: '',
        ctnDigit: 1,
        tareWeight: 1,
        isDeleted: false,
        ctnOwner: ''
      }
    ], //箱型向量复制
    formatBoxs: '', //箱型向量格式化
    atd: undefined, // 开航日期
    deadlinePortTime: undefined, // 截港时间
    deadlineCustomsTime: undefined, // 截关时间
    deadlineOrderTime: undefined, // 截单时间
    marks: undefined, //唛头

    // 特货信息
    showCheck: false,
    isCold: false,
    isDanger: false,
    isOog: false,
    coldTemp: undefined, //冷藏温度
    coldTempUnit: undefined, //冷藏温度
    ventilationRate: undefined, //通风量
    ventilationRateUnit: undefined,
    unno: undefined, //UN NO
    type: undefined, //CLASS NO
    flashTemp: undefined, //闪点
    flashTempUnit: undefined, //闪点单位
    overFrontLength: undefined, //超限-前
    overLeftLength: undefined, //超限-左超
    overBackLength: undefined, //超限-后
    overRightLength: undefined, //超限-右
    overHeightLength: undefined, //超限-高
    cargoUnit: undefined, //尺寸单位
    // 自定义增加
    shipper: undefined, // 发货人
    consignee: undefined, // 收货人
    notifyPerson: undefined, // 通知人
    secondPerson: undefined, // 第二通知人
    cargonList: [], //特种箱数组

    seviceType: [], //服务内容

    feeIncometable: [], //应收
    feeExpandtable: [], //应付
    feeOutertable: [], //超过浏览权限的数据

    // 用于现在装载货物表的数据
    packings: [], //集装箱装载货物列表
    cargonInBoxTableData: [],
    cargonunBoxTableData: [], //未显示的装置货物数据

    // 控制第二通知人是否显示
    showSecondPerson: false
  },

  //初始options
  allOption: {
    loadingPortList: [], //装货港
    receiptPlaceList: [], //装货地点
    transshipmentPortList: [], //中转港
    dischargePortList: [], //卸货港
    unloadingPlaceList: [], //卸货地点
    finalDestinationList: [] //目的地
  },
  // 是否已订舱==>根据流程中订舱是否已有时间
  isBooking: false,
  // 点击编辑可以填写所有信息
  allCanFill: false,
  // 是否点击导出托单的回填操作
  isBackfill: false,
  //页面加载
  loading: false,
  newUser: store.state.auth.user,
  //附件
  fileShow: false,
  routeQuery: {
    id: '',
    title: '',
    establish: false,
    // 是否是页面跳转过来的，保存后将此值设置为false
    isJump: false
  }
})
//初始化数据副本 刷新判断使用
const detailDataCopy = ref({})
// 托运标号
const consignmentNoList = ref([])
// 操作详情和特货信息
const docDetailSpecialBoxNewRef = ref(null)
const docDetailBaseRef = ref(null)
const docDetailFileDialogRef = ref(null)
const docDetailBoxRef = ref(null)
const docDetailInformatonRef = ref(null)
const docDetailFeeRef = ref(null)
// tab切换
function tabClick(val) {
  switch (val) {
    case '装箱信息':
      docDetailBoxRef.value.getAllTableData()
      break
  }
}

//获取当前是否已订舱
function getBookingState(time) {
  state.isBooking = time ? true : false
}

// 关闭当前页面并返回列表
function cancle() {
  refresh()
  state.isBackfill = false
  state.allCanFill = false
  // 如果是创建进来时进行操作
  if (state.routeQuery.establish) {
    state.routeQuery.establish = false
  }
  // Router.closeTab()
  // Router.openTab('/business/bussinessIndex/docWorkNew')
}

/**
 * 初始化 要先获取值后初始化
 */
function initData() {
  docDetailBoxRef.value.getAllTableData()
  state.loading = true
  request
    .get(`/api/sebooking/querybyid`, {
      id: state.routeQuery.id
    })
    .then((res) => {
      if (res.status) {
        if (!res.data.cargonList) {
          res.data.cargonList = []
        }
        state.detailData = JSON.parse(JSON.stringify(res.data))
        if (!state.detailData.shipId) {
          state.detailData.shipId = ''
        }
        // 如果未订舱前需要进行拆分
        if (!state.isBooking) {
          let teuSum = 0
          for (const teuItem of state.detailData.containers) {
            teuSum += teuItem.tareWeight ? teuItem.tareWeight : 1
          }
          let curretntUsepkgs = 0
          let curretntUseGrossWeight = 0
          let curretntUseTeuNumber = 0
          let pkgs = state.detailData.pkgs ? state.detailData.pkgs : 0
          let grossWeight = state.detailData.grossWeight
            ? state.detailData.grossWeight
            : 0
          let measurement = state.detailData.measurement
            ? state.detailData.measurement
            : 0
          state.detailData.containers.forEach((teuSet, index) => {
            let teuNumber = teuSet.tareWeight ? teuSet.tareWeight : 1
            if (index != state.detailData.containers.length - 1) {
              teuSet.pkgs = Math.floor((pkgs / teuSum) * teuNumber)
              teuSet.weight = Math.floor((grossWeight / teuSum) * teuNumber)
              teuSet.measurement = Math.floor(
                (measurement / teuSum) * teuNumber
              )
              curretntUsepkgs += teuSet.pkgs
              curretntUseGrossWeight += teuSet.weight
              curretntUseTeuNumber += teuSet.measurement
            } else {
              teuSet.pkgs = pkgs - curretntUsepkgs
              teuSet.weight = grossWeight - curretntUseGrossWeight
              teuSet.measurement = measurement - curretntUseTeuNumber
            }
          })
        }
        //重置无浏览权限的费用信息
        state.detailData.feeOutertable = []
        state.detailData.isCold = state.detailData.isCold
          ? state.detailData.isCold
          : false
        state.detailData.isDanger = state.detailData.isDanger
          ? state.detailData.isDanger
          : false
        state.detailData.isOog = state.detailData.isOog
          ? state.detailData.isOog
          : false
        state.detailData.showCheck =
          state.detailData.cargoType == '普货' ? false : true
        state.detailData.feeIncometable = []
        state.detailData.feeExpandtable = []
        // 将对应的fee分组成应收应付两个数组
        for (const iterator of state.detailData.fees) {
          if (
            store.state.auth.employee.checkLevel >=
              parseInt(iterator.feeLevel) ||
            !iterator.feeLevel
          ) {
            if (iterator.receivedOrPaid == '应收') {
              state.detailData.feeIncometable.push(iterator)
            } else {
              state.detailData.feeExpandtable.push(iterator)
            }
          } else {
            state.detailData.feeOutertable.push(iterator)
          }
        }
        // 当前箱子表是否有选中的数据
        let currentRow =
          docDetailBoxRef.value.$refs.docDetailBoxPackingTableRef.getState()
            .currentRow
        if (currentRow) {
          let docDetaiBoxState =
            docDetailBoxRef.value.$refs.docDetailBoxCargoLoadingTableRef
          docDetaiBoxState.tableData.boxAndCargoTableData = []
          docDetaiBoxState.rowBoxs = currentRow
          for (const itemPacking of state.detailData.packings) {
            docDetailBoxRef.value.$refs.docDetailBoxCargoLoadingTableRef.tableData.boxAndCargoTableData.push(
              itemPacking
            )
          }
        }
        // 格式化调整服务内容
        state.detailData.seviceType = []
        // IsInsure 对应 保险 编辑时对服务类型对应字段进行转化
        const serviceObj = {
          isNeedTrailer: '拖车（集卡拖车）',
          isToWarehouse: '进仓（干线物流）',
          isToCustoms: '报关',
          isInsure: '保险',
          isBooking: '订舱'
        }
        let serviceObjKeys = Object.keys(serviceObj)
        for (const item of serviceObjKeys) {
          if (state.detailData[item]) {
            state.detailData.seviceType.push(serviceObj[item])
          }
        }
        let containersSumType = {}
        // 将对应的箱子数组重新解构出来
        for (const boxItem of state.detailData.containers) {
          let containerKeys = Object.keys(containersSumType)
          if (containerKeys.indexOf(boxItem.containerSize) === -1) {
            containersSumType[boxItem.containerSize] = {
              count: 1,
              tareWeight: boxItem.tareWeight
            }
          } else {
            containersSumType[boxItem.containerSize].count += 1
          }
        }
        state.detailData.containerSums = []
        const containerKeysList = Object.keys(containersSumType)
        containerKeysList.forEach((itemValue, index) => {
          state.detailData.containerSums.push({
            id: 0,
            index: index,
            bookingId: 0,
            tareWeight: containersSumType[itemValue].tareWeight,
            ctnType: itemValue,
            ctnDigit: containersSumType[itemValue].count,
            isDeleted: false,
            ctnOwner: ''
          })
        })
        state.detailData.containerSumsCopy = JSON.parse(
          JSON.stringify(state.detailData.containerSums)
        )
        //特货信息数据转化
        if (state.detailData.coldDangers.length) {
          state.detailData.coldTemp = state.detailData.coldDangers[0].coldTemp //冷藏温度
          state.detailData.coldTempUnit =
            state.detailData.coldDangers[0].coldTempUnit //冷藏温度
          state.detailData.ventilationRate =
            state.detailData.coldDangers[0].ventilationRate //通风量
          state.detailData.ventilationRateUnit =
            state.detailData.coldDangers[0].ventilationRateUnit
          state.detailData.unno = state.detailData.coldDangers[0].unno //UN NO
          state.detailData.type = state.detailData.coldDangers[0].type //CLASS NO
          state.detailData.flashTemp = state.detailData.coldDangers[0].flashTemp //闪点
          state.detailData.flashTempUnit =
            state.detailData.coldDangers[0].flashTempUnit //闪点单位
          state.detailData.overFrontLength =
            state.detailData.coldDangers[0].overFrontLength //超限-前
          state.detailData.overLeftLength =
            state.detailData.coldDangers[0].overLeftLength //超限-左超
          state.detailData.overBackLength =
            state.detailData.coldDangers[0].overBackLength //超限-后
          state.detailData.overRightLength =
            state.detailData.coldDangers[0].overRightLength //超限-右
          state.detailData.overHeightLength =
            state.detailData.coldDangers[0].overHeightLength //超限-高
          state.detailData.cargoUnit = state.detailData.coldDangers[0].cargoUnit //尺寸单位
        }
        // 收发通转换
        for (const iterator of state.detailData.shipperConsignees) {
          if (iterator.type == '发货人') {
            state.detailData.shipper = iterator.content
          } else if (iterator.type == '收货人') {
            state.detailData.consignee = iterator.content
          } else if (iterator.type == '通知人') {
            state.detailData.notifyPerson = iterator.content
          } else if (iterator.type == '第二通知人') {
            state.detailData.secondPerson = iterator.content
          }
        }
        if (state.detailData.secondPerson) {
          state.detailData.showSecondPerson = true
        } else {
          state.detailData.showSecondPerson = false
        }
        // 箱型箱量处理格式化
        // if (!state.detailData.containerSums.length) {
        //   // state.detailData.containerSums = [
        //   //   {
        //   //     id: 0,
        //   //     bookingId: 0,
        //   //     ctnType: '',
        //   //     ctnDigit: 1,
        //   //     teu: 1,
        //   //     isDeleted: false,
        //   //     ctnOwner: ''
        //   //   }
        //   // ]
        // }
        if (state.detailData.containerSums.length) {
          let boxTypeObj = {}
          for (const iterator of state.detailData.containerSums) {
            let boxKeysList = Object.keys(boxTypeObj)
            if (boxKeysList.indexOf(iterator.ctnType) != -1) {
              boxTypeObj[iterator.ctnType] += iterator.ctnDigit
            } else {
              boxTypeObj[iterator.ctnType] = iterator.ctnDigit
            }
          }
          let operationKeysList = Object.keys(boxTypeObj)
          let boxtypeOfNumber = ''
          operationKeysList.forEach((value, index) => {
            boxtypeOfNumber =
              boxtypeOfNumber + '' + value + 'X' + boxTypeObj[value] + ';'
          })
          state.detailData.formatBoxs = boxtypeOfNumber.substr(
            0,
            boxtypeOfNumber.length - 1
          )
        } else {
          state.detailData.formatBoxs = ''
        }
        // 处理托运标号
        consignmentNoList.value = state.detailData.consignmentNo
          ? state.detailData.consignmentNo.split(',')
          : []
        const portList = [
          'loadingPort',
          'receiptPlace',
          'transshipmentPort',
          'dischargePort',
          'unloadingPlace',
          'finalDestination'
        ]
        for (const iterator of portList) {
          switch (iterator) {
            case 'loadingPort':
              if (state.detailData[iterator]) {
                state.allOption.loadingPortList = [
                  {
                    id: 1,
                    value: state.detailData.loadingPort,
                    label: `${state.detailData.loadingPortCode} | ${state.detailData.loadingPort}`,
                    selectLabel: `${state.detailData.loadingPortCode} | ${state.detailData.loadingPort}`,
                    rigthName: state.detailData.loadingPortCode
                  }
                ]
              }
              break
            case 'receiptPlace':
              if (state.detailData[iterator]) {
                state.allOption.receiptPlaceList = [
                  {
                    id: 1,
                    value: state.detailData.receiptPlace,
                    label: `${state.detailData.receiptPlaceCode} | ${state.detailData.receiptPlace}`,
                    selectLabel: `${state.detailData.receiptPlaceCode} | ${state.detailData.receiptPlace}`,
                    rigthName: state.detailData.receiptPlaceCode
                  }
                ]
              }
              break
            case 'transshipmentPort':
              if (state.detailData[iterator]) {
                state.allOption.transshipmentPortList = [
                  {
                    id: 1,
                    value: state.detailData.transshipmentPort,
                    label: `${state.detailData.transshipmentPortCode} | ${state.detailData.transshipmentPort}`,
                    selectLabel: `${state.detailData.transshipmentPortCode} | ${state.detailData.transshipmentPort}`,
                    rigthName: state.detailData.transshipmentPortCode
                  }
                ]
              }
              break
            case 'dischargePort':
              if (state.detailData[iterator]) {
                state.allOption.dischargePortList = [
                  {
                    id: 1,
                    value: state.detailData.dischargePort,
                    label: `${state.detailData.dischargePortCode} | ${state.detailData.dischargePort}`,
                    selectLabel: `${state.detailData.dischargePortCode} | ${state.detailData.dischargePort}`,
                    rigthName: state.detailData.dischargePortCode
                  }
                ]
              }
              break
            case 'unloadingPlace':
              if (state.detailData[iterator]) {
                state.allOption.unloadingPlaceList = [
                  {
                    id: 1,
                    value: state.detailData.unloadingPlace,
                    label: `${state.detailData.unloadPlaceCode} | ${state.detailData.unloadingPlace}`,
                    selectLabel: `${state.detailData.unloadPlaceCode} | ${state.detailData.unloadingPlace}`,
                    rigthName: state.detailData.unloadPlaceCode
                  }
                ]
              }
              break
            case 'finalDestination':
              if (state.detailData[iterator]) {
                state.allOption.finalDestinationList = [
                  {
                    id: 1,
                    value: state.detailData.finalDestination,
                    label: `${state.detailData.finalDestinationCode} | ${state.detailData.finalDestination}`,
                    selectLabel: `${state.detailData.finalDestinationCode} | ${state.detailData.finalDestination}`,
                    rigthName: state.detailData.finalDestinationCode
                  }
                ]
              }
              break
          }
        }
        detailDataCopy.value = JSON.parse(JSON.stringify(state.detailData))
        state.loading = false
      } else {
        ElMessage.warning(res.message)
      }
    })
}
/**
 * 保存
 */
function getFormPromise(form) {
  return new Promise((resolve) => {
    form.validate((res) => {
      resolve(res)
    })
  })
}

// 保存前的数据处理
function beforeSaveOpration() {
  let detailDataCopy = JSON.parse(JSON.stringify(state.detailData))
  // 合并两个数组
  detailDataCopy.fees = [
    ...detailDataCopy.feeExpandtable,
    ...detailDataCopy.feeIncometable,
    ...detailDataCopy.feeOutertable
  ]
  // 将新增的集装箱货物属于新增的id重置为0
  for (const packingsValue of detailDataCopy.packings) {
    if (packingsValue.id.includes('new')) {
      packingsValue.id = 0
    }
  }
  detailDataCopy.containerSums = detailDataCopy.containerSumsCopy
  let docDetaiBoxState =
    docDetailBoxRef.value.$refs.docDetailBoxCargoLoadingTableRef
  docDetaiBoxState.rowBoxs = ''
  docDetaiBoxState.tableData.boxAndCargoTableData = []
  // 将对应的收发通信息伪装成一个数组插入
  const shipperList = ['shipper', 'consignee', 'notifyPerson', 'secondPerson']
  detailDataCopy.shipperConsignees = []
  for (const iterator of shipperList) {
    let shipperObj = {
      content: '', //内容
      type: '' //类别
    }
    switch (iterator) {
      case 'shipper':
        shipperObj.type = '发货人'
        shipperObj.content = state.detailData.shipper
        break
      case 'consignee':
        shipperObj.type = '收货人'
        shipperObj.content = state.detailData.consignee
        break
      case 'notifyPerson':
        shipperObj.type = '通知人'
        shipperObj.content = state.detailData.notifyPerson
        break
      case 'secondPerson':
        shipperObj.type = '第二通知人'
        shipperObj.content = state.detailData.secondPerson
        break
    }
    detailDataCopy.shipperConsignees.push(shipperObj)
  }
  //将服务类型勾选的对应的类型字段设置为true
  detailDataCopy.IsNeedTrailer = false
  detailDataCopy.IsToWarehouse = false
  detailDataCopy.IsToCustoms = false
  detailDataCopy.IsBooking = false
  for (const iterator of state.detailData.seviceType) {
    switch (iterator) {
      case '订舱':
        detailDataCopy.IsBooking = true
        break
      case '拖车（集卡拖车）':
        detailDataCopy.IsNeedTrailer = true
        break
      case '进仓（干线物流）':
        detailDataCopy.IsToWarehouse = true
        break
      case '报关':
        detailDataCopy.IsToCustoms = true
        break
    }
  }
  // 将特货信息的数据塞入数组
  // detailDataCopy.coldDangers = []
  if (!detailDataCopy.coldDangers.length) {
    detailDataCopy.coldDangers.push({
      id: 0,
      createBy: undefined,
      createTime: undefined,
      updateBy: undefined,
      updateTime: undefined,
      bookingId: undefined,
      coldTemp: state.detailData.coldTemp, //冷藏温度
      coldTempUnit: state.detailData.coldTempUnit, //冷藏温度
      minTemp: 0,
      maxTemp: 0,
      ventilationRate: state.detailData.ventilationRate, //通风量
      ventsDescription: undefined,
      ventilationRateUnit: state.detailData.ventilationRateUnit,
      packagingGroup: undefined,
      imdg: undefined,
      unno: state.detailData.unno, //UN NO
      type: state.detailData.type, //CLASS NO
      flashTemp: state.detailData.flashTemp, //闪点
      flashTempUnit: state.detailData.flashTempUnit, //闪点单位
      emergencyContact: undefined,
      remark: undefined,
      isDangerous: true,
      isDeleted: false,
      ventilationRateUnit: undefined,
      overFrontLength: state.detailData.overFrontLength, //超限-前
      overLeftLength: state.detailData.overLeftLength, //超限-左超
      overBackLength: state.detailData.overBackLength, //超限-后
      overRightLength: state.detailData.overRightLength, //超限-右
      overHeightLength: state.detailData.overHeightLength, //超限-高
      cargoUnit: state.detailData.cargoUnit, //尺寸单位
      overDigit: 0,
      overGrossweight: 0,
      overVolume: 0
    })
  } else {
    const coldDangersKeysList = [
      'coldTemp',
      'coldTempUnit',
      'ventilationRate',
      'ventilationRateUnit',
      'unno',
      'type',
      'flashTemp',
      'flashTempUnit',
      'overFrontLength',
      'overLeftLength',
      'overBackLength',
      'overRightLength',
      'overHeightLength',
      'cargoUnit'
    ]
    for (const valueItem of coldDangersKeysList) {
      detailDataCopy.coldDangers[0][valueItem] = state.detailData[valueItem]
    }
  }
  // 存在箱型箱量未填写的情况
  if (!detailDataCopy.formatBoxs) {
    ElMessage.warning('请填写箱型向量')
    return
  }
  toSaveBill(detailDataCopy)
}

async function save() {
  const baseDataForm = docDetailBaseRef.value.$refs.baseDataForm // 操作信息
  // const specialCargoForm =
  //   docDetailSpecialBoxNewRef.value.$refs.specialCargoForm // 特货信息
  Promise.all([baseDataForm].map(getFormPromise)).then((res) => {
    const validateResult = res.every((item) => !!item)
    if (!validateResult) {
      ElMessage.warning('请检查操作详情是否存在未填写')
      return
    }
    beforeSaveOpration()
  })
}

function toSaveBill(saveData) {
  request.post('/api/sebooking/modifyBooking', saveData).then((res) => {
    if (res.status) {
      docDetailFeeRef.value.docDetailFeeInRef.state.rowIndex = -1
      docDetailFeeRef.value.docDetailFeeInRef.state.columnIndex = -1
      docDetailFeeRef.value.docDetailFeeExRef.state.columnIndex = -1
      docDetailFeeRef.value.docDetailFeeExRef.state.rowIndex = -1
      if (state.routeQuery.establish || state.routeQuery.isJump) {
        ElMessage.success('保存至草稿成功')
        Router.closeAndRefreshTab({
          path: '/business/bussinessIndex/docWorkNewdetail',
          query: {
            id: state.routeQuery.id,
            title: `订舱详情`,
            establish: false,
            isJump: false
          }
        })
        // Router.closeTab()
      } else {
        ElMessage.success(res.message)
        refresh()
      }
      state.allCanFill = false
      state.isBackfill = false
    } else {
      ElMessage.error(res.message)
    }
  })
}
/**
 * 附件
 */
// function openUploadfile() {
//  if (state.routeQuery.iscopy) {
//     ElMessage.warning('请先保存')
//   } else {
//     state.fileShow = true
//     docDetailFileDialogRef.value.getFileTableData()
//   }
// }
/**
 * 刷新
 */
function refresh() {
  initData()
  docDetailInformatonRef.value.getStepData()
}

function refreshStep() {
  docDetailInformatonRef.value.getStepData()
}

onMounted(() => {
  vueBus.off('refreshBussiness' + Route.query.id)
  vueBus.on('refreshBussiness' + Route.query.id, (val) => {
    refresh()
  })
  if (Route.query != {}) {
    store.dispatch('tab/modifyTabTitle', {
      path: Route.fullPath,
      title: Route.query.title
    })
    state.routeQuery.id = Route.query.id
    state.routeQuery.title = Route.query.title
    state.routeQuery.establish = Route.query.establish == 'true' ? true : false
    state.routeQuery.isJump = Route.query.isJump == 'true' ? true : false
    initData()
    state.activeName = Route.query.tab
  }
})
</script>

<style lang="scss" scoped>
.tab {
  margin-bottom: 8px;
}

.container {
  display: flex;
  flex-direction: column;

  .content {
    flex: 1;
    height: auto;
    padding: 0 0 8px 0;
  }

  :deep(.el-radio-group) {
    height: 24px;
  }

  :deep(.el-radio) {
    margin-right: 15px;

    .el-radio__inner {
      width: 12px;
      height: 12px;
    }

    .el-radio__label {
      font-size: 12px;
    }
  }

  :deep(.el-form-item) {
    width: 100%;
  }

  :deep(.el-date-editor) {
    width: 100%;
  }

  :deep(.el-tabs) {
    height: 100%;

    .el-tabs__item {
      font-family: PingFang SC;
      font-weight: bold;
      font-size: 14px;
      letter-spacing: 0px;
    }

    .el-tabs__nav-scroll .el-tabs__item:nth-child(2) {
      padding-left: 12px;
    }

    .el-tabs__header {
      padding: 0px;
      margin-bottom: 0px;
    }

    .el-tabs__content {
      height: calc(100% - 55px);

      .el-tab-pane {
        height: 100%;
      }
    }
  }

  .form {
    height: 100%;
  }
}

.tab-all-container {
  background: #ffffff;

  :deep(.el-tabs--border-card > .el-tabs__content) {
    padding: 16px;
  }
  // border-bottom: 2px solid #e7e7e7;
}
</style>
